package cn.shengchao.cap.domain.order;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.shengchao.cap.domain.token.CapProperties;
import cn.shengchao.cap.domain.token.CapTokenUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import top.continew.starter.core.exception.BaseException;

/**
 * @program: examstarapi
 * @description: 高考志愿填报订单提交
 * @author: Xiong weiqiang
 * @create: 2025-05-21 15:52
 */
@Component
@RequiredArgsConstructor
public class CapOrderUtils {
    private final CapTokenUtil tokenUtil;
    private static final String ORDER_CREATE_REQ_URL = "/api/v1/Platform/createorder";
    @Transactional
    public String createOrder(CapOrderCreateDto dto) {
        CapProperties capProperties= SpringUtil.getBean(CapProperties.class );
        if (capProperties==null||capProperties.getApiKey()==null){
            throw new BaseException("高考志愿填报服务的配置错误，无法调用");
        }
        // 获取token
        String token = tokenUtil.getToken();
        if (StrUtil.isNotBlank(token)) {
            HttpRequest post = HttpUtil.createPost(capProperties.getServerUrl() + ORDER_CREATE_REQ_URL).header("Authorization", token).body("orderCode=" + dto.getOrderCode() + "&userName=" + dto.getUserName() + "&graduationYear=" + dto.getGraduationYear());
            try (HttpResponse response = post.execute()) {
                if (response.isOk()) {
                    String data = response.body();
                    System.out.println("Response body: " + data);
                    JSONObject jsonObject = new JSONObject(data);
                    if ("200".equals(jsonObject.getStr("code")) && "true".equals(jsonObject.getStr("success"))) {
                        return jsonObject.getJSONObject("data").getStr("orderCode");
                    }
                }
            }
        }
        // 创建订单失败
        return null;
    }
}